package com.scm.biz.service._impl;

import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.scm.biz.action.BaseAction;
import com.scm.biz.bean.Customer;
import com.scm.biz.bean.SysRole;
import com.scm.biz.dao.BusinessConstantDao;
import com.scm.biz.dao.ConstantDao;
import com.scm.biz.dao.CustomerDao;
import com.scm.biz.dao.SysRoleDao;
import com.scm.biz.enums.FileCategoryEnum;
import com.scm.biz.query.customer.CustomerQuery;
import com.scm.biz.result.CustomerResult;
import com.scm.biz.service.BusinessConstantService;
import com.scm.biz.service.BusinessFileService;
import com.scm.biz.service.CustomerContactService;
import com.scm.biz.service.CustomerService;
import com.scm.core.bean.exp.UfdmException;
import com.scm.utils.Const;

/**
 * 客户类的服务类实现类
 * @author Young
 * @Date 2016.11.15
 *
 */
@Service("customerService")
public class CustomerServiceimpl implements CustomerService{
	
	@Resource
	private CustomerDao customerDao;
	
	@Resource
	private ConstantDao constantDao;
	
	@Resource
	private BusinessConstantDao businessConstantDao;
	
	@Resource
	private BusinessFileService businessFileService;
	
	@Resource
	private CustomerContactService customerContactService;
	
	@Resource
	private BusinessConstantService businessConstantService;
	
	@Resource
	private SysRoleDao sysRoleDao;

	@Override
	public CustomerResult getById(int id) {
		return customerDao.selectById(id);
	}

	@Override
	public List<CustomerResult> getList(CustomerQuery customerQuery) {
		if(customerQuery !=null){
			setQuery(customerQuery);
		}
		Integer userId=(Integer)BaseAction.doGetSession("userId");
		customerQuery.setCreator(userId);
		List<SysRole> roles=sysRoleDao.selectListByUserId(userId);
		for(SysRole role:roles){
			//判断是否拥有总监角色
			if(role.getName().indexOf("总监")!=-1){
				customerQuery.setCreator(null);
				break;
			}
		}
		return customerDao.selectList(customerQuery);
	}
	
	/**
	 * 将查询参数设置到查询对象中
	 * @param customerQuery
	 */
	private void setQuery(CustomerQuery customerQuery) {
		if(customerQuery.getStyleLabels()!=null&&!customerQuery.getStyleLabels().trim().isEmpty()){
			String[] str=customerQuery.getStyleLabels().trim().split(Const.SPLIT);
			customerQuery.setStyleLabelCount(str.length);
			customerQuery.setStyleLabel(Arrays.asList(str));
		}
		if(customerQuery.getProductCategorys()!=null&&!customerQuery.getProductCategorys().trim().isEmpty()){
			String[] str=customerQuery.getProductCategorys().trim().split(Const.SPLIT);
			customerQuery.setProductCategoryCount(str.length);
			customerQuery.setProductCategory(Arrays.asList(str));
		}
	}

	@Override
	public int getTotalByQuery(CustomerQuery customerQuery) {
		setQuery(customerQuery);
		return customerDao.selectTotalByQuery(customerQuery);
	}

	@Override
	public void save(MultipartHttpServletRequest req,Customer customer) throws UfdmException {
		customer.setCode(Const.getCustomerCode());
		Date date=new Date();
		customer.setCreateAt(date);
		customer.setFullname(customer.getFullname().trim());
		customerDao.insert(customer);
		//获取联系人，并保存
		String contacts=req.getParameter("contacts");
		customerContactService.save(contacts,customer.getId());
		//保存数据到附件-客户对应表
		List<MultipartFile> attachs=req.getFiles("attachs");
		businessFileService.insertList(attachs, customer.getId(), FileCategoryEnum.CUSTOMER_FILE.value(), 0);
		//保存客户产品分类标签
		String productCategory=req.getParameter("productCategory");
		businessConstantService.save(productCategory, customer.getId(), FileCategoryEnum.CUSTOMER_PRODUCT_CATEGORY.value());
		//保存客户标签风格标签
		String styleLabel=req.getParameter("styleLabel");
		businessConstantService.save(styleLabel, customer.getId(), FileCategoryEnum.CUSTOMER_STYLELABLE.value());
	}
	
	@Override
	public int modifyById(MultipartHttpServletRequest req,Customer customer) throws UfdmException {
		removeAssociationTags(customer.getId().intValue());
		Date date=new Date();
		customer.setUpdateAt(date);
		customer.setFullname(customer.getFullname().trim());
		customerContactService.removeByCustomerId(customer.getId().intValue());
		//获取联系人，并保存
		String contacts=req.getParameter("contacts");
		customerContactService.save(contacts,customer.getId());
		//保存数据到附件-客户对应表
		List<MultipartFile> attachs=req.getFiles("attachs");
		String attachIds=req.getParameter("attachId");
		String delAttachIds=req.getParameter("delAttachIds");
		//删除附件
		businessFileService.removeCustomerFile(delAttachIds);
		//保存新上传和更改的附件
		businessFileService.saveCustomer(attachIds, attachs, customer.getId().intValue(),FileCategoryEnum.CUSTOMER_FILE.value());
		
		//保存客户产品分类标签
		String productCategory=req.getParameter("productCategory");
		businessConstantService.save(productCategory, customer.getId(), FileCategoryEnum.CUSTOMER_PRODUCT_CATEGORY.value());
		//保存客户标签风格标签
		String styleLabel=req.getParameter("styleLabel");
		businessConstantService.save(styleLabel, customer.getId(), FileCategoryEnum.CUSTOMER_STYLELABLE.value());
		return customerDao.updateById(customer);
	}

	/**
	 * 删除客户管理的标签
	 * @param 
	 */
	private void removeAssociationTags(int customerId) {
		//删除产品分类
		businessConstantDao.deleteByCustomerId(customerId,FileCategoryEnum.CUSTOMER_PRODUCT_CATEGORY.value());
		//删除风格分类
		businessConstantDao.deleteByCustomerId(customerId,FileCategoryEnum.CUSTOMER_STYLELABLE.value());
	}

	@Override
	public int removeById(int id) {
		removeAssociationTags(id);
		customerContactService.removeByCustomerId(id);
		businessFileService.removeByBusinesId(Long.valueOf(id), FileCategoryEnum.CUSTOMER_FILE.value());
		return customerDao.deleteById(id);
	}

	@Override
	public int getByFullname(Long id,String fullname) {
		Map<String,Object> map=new HashMap<String,Object>();
		map.put("id", id);
		map.put("fullname", fullname);
		return customerDao.selectByFullname(map);
	}

	@Override
	public int getByAbbreviation(Long id,String abbreviation) {
		Map<String,Object> map=new HashMap<String,Object>();
		map.put("id", id);
		map.put("abbreviation", abbreviation);
		return customerDao.selectByAbbreviation(map);
	}

	@Override
	public List<Map<String, Object>> getCustomerByName(String name) {
		return customerDao.getCustomerByName(name);
	}

	@Override
	public List<Map<String, Object>> getAllCustomer() {
		return customerDao.getAllCustomer();
	}

	@Override
	public List<Customer> selectList() {
		return customerDao.selectAll();
	}

	@Override
	public int getTotal() {
		return customerDao.selectTotal();
	}

	@Override
	public int getSignedCustomerCount() {
		return customerDao.selectSignedCustomerCount();
	}

}
